package cn.diancan.util.print;

import cn.diancan.util.DateUtil;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import javax.imageio.ImageIO;


public class PrintUtil {
	
    public static boolean print(ProductPrint pro){
		return print0(pro);
    }
	 
	
	public static boolean print0(ProductPrint pro){ 
		
		int height = pro.getHeight();//175 + 3 * 15 + 20;
		int width = pro.getWidth();

		// 通俗理解就是书、文档
		Book book = new Book();

		// 打印格式
		PageFormat pf = new PageFormat();
		pf.setOrientation(PageFormat.PORTRAIT);

		// 通过Paper设置页面的空白边距和可打印区域。必须与实际打印纸张大小相符。
		Paper p = new Paper();
		p.setSize(width, height);
		p.setImageableArea(pro.getX(), pro.getY(), width, height);
		pf.setPaper(p);

		// 把 PageFormat 和 Printable 添加到书中，组成一个页面
		book.append(pro, pf);

		// 获取打印服务对象
		PrinterJob job = PrinterJob.getPrinterJob();
		job.setPageable(book); 
		try {
			job.print();
			return true;
		} catch (PrinterException e) {
			e.printStackTrace();
			System.out.println("================打印出现异常");
		}
		return false;
	}
	
	public static void main(String[] args) {
	    ProductPrint pro = new ProductPrint(  "1234561", DateUtil.currentDate(),"JMHS1198", "0932","湖北省黄石市阳新县五马坊步行街" ,"女人100","女人100品牌店", "---", 69d, 69d, null,69d, null, 0d, 1);
	    PrintUtil.printImageTest(pro);

	    //PrintUtil.print(pro);
	}
	
	 
	
	public static boolean printImageTest(ProductPrint pro)  { 
		try {
			int width = pro.getWidth();
			int height = pro.getHeight();
			BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); 
			Graphics2D g2d =image.createGraphics();  
			
			pro.draw(g2d); 
			//释放对象  
			g2d.dispose();  
			// 保存文件      
			ImageIO.write(image, "png", new File("D:/101/"+System.currentTimeMillis()+".png"));
		} catch (IOException e) { 
			e.printStackTrace();
		}
		return true;
	}

}
